<?php

namespace App\Console\Commands;

use Illuminate\Support\Carbon;
use Illuminate\Console\Command;

class AutoSaleReportScript extends Command
{
    /**
     * The name and signature of the console command.
     * run: php artisan command:AutoSaleReportScript.
     *
     * @var string
     */
    protected $signature = 'command:AutoSaleReportScript';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $url        = env('SCRIPT_API');
        while (true) {
            $startDay =  '2025-09-01';
            $endDay   =  '2025-09-30';
            $diffDays = Carbon::parse($startDay)->diffInDays(Carbon::parse($endDay));
            if ($diffDays) {
                for ($i = 0; $i <= $diffDays; ++$i) {
                    $day     = Carbon::parse($endDay)->subDays($i)->format('Y-m-d');
                    // 记录请求开始时间
                    $startTime = microtime(true);
                    $headers   = [
                        'Center-Token: eyJpdiI6IkNOcUZuYit4NVwvOG54XC9OSnNwT2NQQT09IiwidmFsdWUiOiJUUWtsSU90OTZwSVYxRHA1ZnBvQ1g5T3BmRUQrRVFWWjhxcGVQd2NFTE5oM0lLbnFZXC81RW1NdHNRbnZJSTNoeGIrS0JDVFhPN2poZERKQ29oZDhRYzBUN0R6MVNKNU5vVWo0Z0ROMzhqZkRWXC8yak5vSnJRVEREU2d1ZGpxXC8wVWN4Vkl2RDErZHNtdXNhSURlMnRqRFI0RTh4NEF0NFwvY0NrWkR0K3IxZktMazlvZkxIMWRicHNsYlpCRFdpRlJCOVhtZHM3TWt1QTU2TGFLb0swV01SZz09IiwibWFjIjoiYzI2OGM2YWU3ZDQyNzQ3YTk0NGNjNmU2ZThhNWVmNzJlYjYzZDBmZTMzNGI5ZjhkYTY5NDk4MDdhMmUxMTVlZSJ9', // 设置内容类型
                    ];
                    $res       = $this->curl($url, ['start_day' => $day, 'end_day' => Carbon::parse($day)->addDay()->format('Y-m-d')], $headers);
                    // 计算请求耗时
                    $endTime     = microtime(true);
                    $elapsedTime = round(($endTime - $startTime), 2); // 转换为毫秒，保留2位小数

                    //执行过程中在控制台输出结果，包含请求时间
                    echo "统计日期 {$day}: 耗时 {$elapsedTime}s - " . json_encode($res, 64 | 256) . PHP_EOL;
                }

                break;
            }
        }
        dd('ok');
    }

    private function curl($url, $postData = [], $headers = [])
    {
        // 初始化 cURL 会话
        $ch = curl_init();

        // 设置 cURL 选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回请求结果而不是直接输出
        curl_setopt($ch, CURLOPT_POST, true); // 设置为 POST 请求
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 关闭 SSL 认证（仅用于测试，生产环境建议开启）
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 设置 POST 请求的数据
        $headers && curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        // 执行 cURL 请求
        $response = curl_exec($ch);

        // 检查 cURL 错误
        if (curl_errno($ch)) {
            $error_message = curl_error($ch);
            curl_close($ch);

            return ['error' => $error_message];
        }

        // 关闭 cURL 会话
        curl_close($ch);

        // 假设响应是 JSON 格式
        return json_decode($response, true);
    }
}
